// const baseURL = process.env.VUE_APP_BASE_API;
import { Loading, Message } from "element-ui";
import axios from "axios";

// 回显数据字典
export function selectDictLabel(datas, value) {
  var actions = [];
  Object.keys(datas).map(id => {
    if (datas[id].itemValue == "" + value) {
      actions.push(datas[id].itemText);
      return false;
    }
  });
  return actions.join("");
}

// 通用下载方法
// export function download(fileName) {
//   window.location.href =
//     axios.defaults.baseURL +
//     "/common/download?fileName=" +
//     encodeURI(fileName) +
//     "&delete=" +
//     true;
// }

//手机正则验证
export function checkPhone(phone) {
  if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(phone)) {
    alert("手机号码有误，请重填");
    return false;
  }
}

//验证是否数字
export function isNumber(o) {
  return Object.prototype.toString.call(o).slice(8, -1) === "Number";
}

//GTM时间格式转为普通格式
export function GMTToStr(time) {
  let date = new Date(time);
  let Str =
    date.getFullYear() +
    "-" +
    (date.getMonth() + 1) +
    "-" +
    date.getDate() +
    " " +
    date.getHours() +
    ":" +
    date.getMinutes() +
    ":" +
    date.getSeconds();
  return Str;
}

/**
 * 下载附件（token）
 * @param {*} http
 * @param {*} pathUrl
 * @param {*} searchList
 * @param {*文件名} name
 */
export function downloadFile(http, pathUrl, name, format) {
  // 获取时间，这一步是在下载时文件名带下载日期，例如：用户信息2020-04-27.xls,如无需要可以去掉
  // let d = new Date();
  // let month = d.getMonth() + 1;
  // let day = d.getDate();
  // let time =
  //   d.getFullYear() +
  //   "-" +
  //   (String(month).length > 1 ? month : "0" + month) +
  //   "-" +
  //   (String(day).length > 1 ? day : "0" + day);
  // 地址
  let baseURL = axios.defaults.baseURL; // 域名
  const PATH = {
    userList: pathUrl // 后台接口地址
  };

  // 参数
  function createObjectURL(object) {
    return window.URL
      ? window.URL.createObjectURL(object)
      : window.webkitURL.createObjectURL(object);
  }

  var xhr = new XMLHttpRequest();
  var formData = new FormData();
  if (http == "get") {
    xhr.open("get", baseURL + PATH.userList); // url填写后台的接口地址
  } else {
    xhr.open("post", baseURL + PATH.userList); //如果是post，在formData append参数
    // Object.keys(searchList).map(key => {
    //   formData.append(key, searchList[key]);
    // });
  }
  xhr.setRequestHeader("COOKIE_TOKEN", localStorage.getItem("token"));
  xhr.responseType = "blob";
  xhr.onload = function() {
    if (this.status === 201) {
      var blob = this.response;
      // xls文件名称
      var filename = `${name}.${format}`;
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, filename);
      } else {
        var a = document.createElement("a");
        var url = createObjectURL(blob);
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
      }
    } else {
      Message.error("下载失败");
    }
  };
  xhr.send(formData);
}

/**
 *
 * @param {*下载方式} http
 * @param {*链接地址} pathUrl
 * @param {*导出请求参数} searchList
 * @param {*下载的名字} xlsName
 * * @param {*传参格式} type
 */
export function expotOut(http, pathUrl, searchList, xlsName, type = ".xls") {
  // 获取时间，这一步是在下载时文件名带下载日期，例如：用户信息2020-04-27.xls,如无需要可以去掉
  let d = new Date();
  let month = d.getMonth() + 1;
  let day = d.getDate();
  let time =
    d.getFullYear() +
    "-" +
    (String(month).length > 1 ? month : "0" + month) +
    "-" +
    (String(day).length > 1 ? day : "0" + day);
  // 地址
  let baseURL = axios.defaults.baseURL; // 域名
  const PATH = {
    userList: pathUrl // 后台接口地址
  };
  // 参数
  let params = "";
  for (let key in searchList) {
    if (searchList[key] == null) {
      delete searchList[key];
    }
  }
  let arr = Object.keys(searchList);
  if (arr.length !== 0) {
    params = "?";
  }
  for (let key in searchList) {
    params = params + key + "=" + searchList[key] + "&";
  }

  function createObjectURL(object) {
    return window.URL
      ? window.URL.createObjectURL(object)
      : window.webkitURL.createObjectURL(object);
  }

  var xhr = new XMLHttpRequest();
  var formData = new FormData();
  if (http == "get") {
    xhr.open("get", baseURL + PATH.userList + params); // url填写后台的接口地址
  } else {
    xhr.open("post", baseURL + PATH.userList); //如果是post，在formData append参数
    Object.keys(searchList).map(key => {
      formData.append(key, searchList[key]);
    });
  }
  xhr.setRequestHeader("COOKIE_TOKEN", localStorage.getItem("token"));
  // if(type == "1") {
  // xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  // }
  xhr.responseType = "blob";
  xhr.onload = function() {
    if (this.status === 200) {
      var blob = this.response;
      // xls文件名称
      var filename = `${xlsName}${time}${type}`;
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, filename);
      } else {
        var a = document.createElement("a");
        var url = createObjectURL(blob);
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
      }
    } else {
      alert("导出失败");
    }
  };
  xhr.send(formData);
}


/**
 *
 * @param {*下载方式} http
 * @param {*链接地址} pathUrl
 * @param {*导出请求参数} searchList
 * @param {*下载的名字} xlsName
 * * @param {*传参格式} type
 * 此方法是后端传输类型为body
 */
export function expotOutBody(http, pathUrl, data, xlsName) {
  // 获取时间，这一步是在下载时文件名带下载日期，例如：用户信息2020-04-27.xls,如无需要可以去掉
  let d = new Date();
  let month = d.getMonth() + 1;
  let day = d.getDate();
  let time =
    d.getFullYear() +
    "-" +
    (String(month).length > 1 ? month : "0" + month) +
    "-" +
    (String(day).length > 1 ? day : "0" + day);
  // 地址
  let baseURL = axios.defaults.baseURL; // 域名
  const PATH = {
    userList: pathUrl // 后台接口地址
  };

  function createObjectURL(object) {
    return window.URL
      ? window.URL.createObjectURL(object)
      : window.webkitURL.createObjectURL(object);
  }

  var xhr = new XMLHttpRequest();
  xhr.open("post", baseURL + PATH.userList);
  xhr.setRequestHeader("COOKIE_TOKEN", localStorage.getItem("token"));
  xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  xhr.responseType = "blob";
  xhr.onload = function() {
    if (this.status === 200) {
      var blob = this.response;
      // xls文件名称
      var filename = `${xlsName}${time}.xls`;
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, filename);
      } else {
        var a = document.createElement("a");
        var url = createObjectURL(blob);
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
      }
    } else {
      alert("导出失败");
    }
  };
  xhr.send(JSON.stringify(data));
}


// 下载数据流文件
export function donwLoadLiu(res) {
  let disposition = res.headers["content-disposition"];
  let fileName = disposition.substring(
    disposition.indexOf("filename=") + 10,
    disposition.length - 1
  );
  let blob = new Blob([res.data], { type: "application/zip" });
  let objectUrl = URL.createObjectURL(blob);
  let a = document.createElement("a");
  a.href = objectUrl;
  a.download = fileName;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

//动画加载loading
export function loadingFull() {
  return Loading.service({
    lock: true,
    text: "Loading",
    spinner: "el-icon-loading",
    background: "rgba(0, 0, 0, 0.7)"
  });
}

export function checkPermiss(code, arr) {
  let index = arr.indexOf(code);
  if (index == -1) {
    // console.log(code,false)
    return false;
  } else {
    // console.log(code,true)
    return true;
  }
}

/**
 * 判断参数时间是否大于指定时间
 * @param date [beginDateStr] [开始日期] yyyy-MM-dd
 * @param date [endDateStr] [结束日期] yyyy-MM-dd
 * @return Boolean
 */
export function isDiffDate(DateStr, paramDateStr) {
  const dateStr = new Date(DateStr.replace(/-/g, "/"));
  const pDateStr = new Date(paramDateStr.replace(/-/g, "/"));
  // console.log(dateStr, pDateStr);
  if (dateStr > pDateStr) {
    return true;
  }
  return false;
}


// -----------------------------------------上传大文件视频test-------------------------------
export function tUploader(props) {
  var uploader = new plupload.Uploader({
    runtimes: "html5,flash,silverlight,html4",
    browse_button: "selectfiles",
    //multi_selection: false,
    container: document.getElementById("container"),
    url: "http://oss.aliyuncs.com",

    init: {
      PostInit: function() {

      },

      FilesAdded: function(up, files) {

      },

      BeforeUpload: function(up, file) {

      },

      UploadProgress: function(up, file) {

      },

      FileUploaded: function(up, file, info) {
        props.success && props.success(up, file, info);
      },

      Error: function(up, err) {
        console.log("err", err);
      }
    }
  });
  uploader.init();
  return uploader;
}

// -----------------------------------------test-------------------------------
/**
 * 下载表格模板
 * @param {*请求方式} http
 * @param {*链接地址} pathUrl
 * @param {*参数 } param
 * @param {*下载的名字} xlsName
 * * @param {*文件格式} type
 * */
export function downloadFormTemp(method, pathUrl, param, xlsName, type) {
  let baseURL = axios.defaults.baseURL; // 域名
  fetch(baseURL + pathUrl, {
    headers: {
      "Content-Type": "application/json",
      "Cookie_token": localStorage.getItem("token"),
      mode: "no-cors"
    },
    method: method,
    body: JSON.stringify(param)
  }).then(res => res.blob())
    .then(blob => {
      var a = document.createElement("a");
      var url = window.URL.createObjectURL(blob);
      a.href = url;
      a.download = xlsName + type;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
    }).catch(() => {
    alert("下载失败");
  });
}

// 获取当前日期时间
export function getNowTimeFull() {
  var myDate = new Date;
  var year = myDate.getFullYear(); //获取当前年
  var mon = myDate.getMonth() + 1 < 10 ? "0" + (myDate.getMonth() + 1) : myDate.getMonth() + 1; //获取当前月
  var date = myDate.getDate() < 10 ? "0" + myDate.getDate() : myDate.getDate(); //获取当前日
  // var hour = myDate.getHours() < 10 ? "0" + myDate.getHours() : myDate.getHours();//获取当前时
  // var minute = myDate.getMinutes() < 10 ? "0" + myDate.getMinutes() : myDate.getMinutes();//获取当前分
  return year + "-" + mon + "-" + date;
}

